//: [Previous](@previous)
/*:
 
 #67 [Add Binary](https://leetcode.com/problems/add-binary/description/)
 
 Given two binary strings, return their sum (also a binary string).
 
 The input strings are both `non-empty` and contains only characters 1 or 0.
 
 Example 1:
 ```
 Input: a = "11", b = "1"
 Output: "100"
 ```
 
 Example 2:
 ```
 Input: a = "1010", b = "1011"
 Output: "10101"
 ```
 
 */

class Solution {
    func addBinary(_ a: String, _ b: String) -> String {
        
        var i = a.count - 1
        var j = b.count - 1
        var carry = 0
        var newString = ""
        
        while i >= 0 || j >= 0 {
            var sum = 0
            if i >= 0 {
                sum += Int(String(a[i])) ?? 0
                i -= 1
            }
            if j >= 0 {
                sum += Int(String(b[j])) ?? 0
                j -= 1
            }
            sum += carry
            
            newString += "\(sum%2)"
            carry = sum / 2
        }
        
        if carry > 0 {
            newString += "\(carry)"
        }
        
        return String(newString.reversed())
    }
}

print(Solution().addBinary("11", "1"))
print(Solution().addBinary("1010", "1011"))

//: [Next](@next)
